<?php

namespace shisou\tpinit\lib;

use GuzzleHttp\Client;
use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\facade\Filesystem;
use think\facade\Log;

class Qiniu
{
    /**
     * 文件上传到七牛云
     */
    /**
     * 图片上传
     */
    public function upload($file)
    {
        $qiniu = config('upload.qiniu');

        $tmpName = $qiniu['project'] . '/' . date('YmdHis') . rand(1000, 9999) . '.' . $file->getOriginalExtension();

        $filePath = $file->getRealPath();

        $token = (new Auth($qiniu['accessKey'], $qiniu['secretKey']))->uploadToken($qiniu['bucket']);

        $policy   = [];
        $checkCrc = false;
        if ($file->getSize() >= (50 * 1024 * 1024)) {
            // 上传策略，参考文档 https://developer.qiniu.com/kodo/manual/put-policy
            $policy   = [
                'returnBody' => '{"key": $(key), "hash": $(etag), "size": $(fsize), "bucket": $(bucket), "name": $(fname)}',
            ];
            $checkCrc = true;
        }

        try {
            $info = (new UploadManager())->putFile($token, $tmpName, $filePath, null, $policy, $checkCrc);
        } catch (\Exception $e) {
            return $e->getMessage();
        }

        return $qiniu['domain'] . '/' . $info[0]['key'];
    }

    /**
     * 视频第一帧
     * @param $url
     * @param $thumb
     * @return array
     */
    public function videoInfo($url, $thumb = [])
    {
        $client    = new Client(['headers' => ["Content-Type" => 'application/x-www-form-urlencoded']]);
        $response  = $client->request('get', $url . '?avinfo');
        $videoInfo = json_decode($response->getBody()
            ->getContents(), true);

        // 获取第一帧
        $vframeUrl = '?vframe/jpg/offset/0';
        if ($thumb) {
            $vframeUrl = '?vframe/jpg/offset/1/w/' . $thumb[0] . '/h/' . $thumb[1];
        }
        // 获取时长
        $duration = date('i:s', $videoInfo['format']['duration']);

        return [
            'video'     => $url,
            'img_cover' => $url . $vframeUrl,
            // 第一帧 URL
            'duration'  => $duration,
        ];
    }
}
